package com.tanhua.common.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.common.config.AliyunConfig;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * * @title: PicUploadService
 *
 * @Author Philcan
 * @Date: 2021/8/8 17:01
 * @Version 1.0
 */
@Service
public class PicUploadService {
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
    @Autowired
    private OSSClient ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;

    public PicUploadResult upload(MultipartFile file) {
        PicUploadResult result = new PicUploadResult();
        boolean isLegal = false;
        for (String s : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), s)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            result.setStatus("error");
            return result;
        }
//        文件新路径
        String fileName = file.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            result.setStatus("error");
            return result;
        }
        result.setStatus("done");
        result.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        result.setUid(String.valueOf(System.currentTimeMillis()));
        return result;
    }

    private String getFilePath(String fileName) {
        DateTime time = new DateTime();
        return "images/" + time.toString("yyyy") + "/" + time.toString("MM") + "/" + time.toString("dd") + "/" +
                System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(fileName, ".");

    }
}
